<template>
  <view class="grid grid-cols-12 gap-2 w-full">
    <view
      v-for="(url, index) in displayUrls"
      :key="index"
      :class="[
        'relative rounded-lg overflow-hidden bg-gray-100',
        index === 0 ? 'row-span-2 col-span-6' : 'col-span-3',
      ]"
    >
      <template v-if="url">
        <image
          :src="url"
          mode="aspectFill"
          class="w-full h-full object-cover border-2 border-gray-200"
          @tap="ImgUpload(url)"
        />
        <view
          class="absolute top-1 right-1 w-6 h-6 bg-black bg-opacity-50 rounded-full flex items-center justify-center cursor-pointer"
          @tap.stop="handleDelete(url)"
        >
          <text class="text-white text-sm">×</text>
        </view>
      </template>
      <template v-else>
        <view
          class="w-full h-full flex items-center justify-center cursor-pointer hover:bg-gray-200 transition-colors"
          @tap="ImgUpload()"
        >
          <view class="text-gray-400">
            <view class="i-carbon-add text-3xl mb-2"></view>
            <text class="text-sm">点击上传</text>
          </view>
        </view>
      </template>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ImgUpload } from '@/services/images'
import { useMemberStore } from '@/stores/modules/member'
const memberStore = useMemberStore()

// 处理删除事件
const handleDelete = (url: string) => {
  // 将图片列表分割成数组
  const imgArray = memberStore.profile!.imgList!.split(',').filter((item) => item)
  // 找到并删除要删除的图片
  const index = imgArray.indexOf(url)
  if (index !== -1) {
    imgArray.splice(index, 1)
    // 重新组合成字符串并更新
    memberStore.profile!.imgList = imgArray.join(',')
    memberStore.updateProfile(memberStore.profile!)
  }
}

// 计算显示的URL列表，包括占位
const displayUrls = computed(() => {
  // 过滤掉空字符串，确保只有有效的URL
  const urls = memberStore.profile!.imgList!.split(',').filter((item) => item)
  // 添加空占位符直到达到最大数量
  while (urls.length < 5) {
    urls.push('')
  }
  return urls
})
</script>

<style scoped>
.grid {
  aspect-ratio: 4/3;
}
</style>
